import {Form, Modal, Row, Col, Input, Select, Cascader, message, Space} from 'antd';
import {useEffect, useState} from 'react';
import {connect} from 'umi';
import jsonp from 'fetch-jsonp';
import {bmap_ak} from '@/requestErrorConfig'

let timeout;
let currentValue;

const fetch = (regionName, value, callback) => {
  if (timeout) {
    clearTimeout(timeout);
    timeout = null;
  }
  currentValue = value;
  const fake = () => {
    jsonp(`https://api.map.baidu.com/place/v2/suggestion?query=${value}&region=${regionName}&city_limit=true&output=json&ak=${bmap_ak}`)
      .then((response) => response.json())
      .then((d) => {
        if (currentValue === value) {
          const {result} = d;
          callback(result);
        }
      });
  };
  if (value) {
    timeout = setTimeout(fake, 300);
  } else {
    callback([]);
  }
};

const LocationForm = (props) => {
  const {dispatch, submitting, regionTree, regionList} = props;
  const {locationForm, setLocationForm, tablePayload, setTablePayload} = props.data;
  const [form] = Form.useForm();

  const [value, setValue] = useState();
  const [addrList, setAddrList] = useState([]);

  /* 初始化表单数据 */
  useEffect(() => {
    if (!locationForm || !locationForm.data) {
      form.setFieldsValue({});
    }
    if (locationForm && locationForm.data) {
      form.setFieldsValue({
        ...locationForm.data,
      });
    }
  }, [locationForm, form]);

  /* 确定操作 */
  function onOk() {
    form.validateFields().then(values => {
      if (submitting) {
        return;
      }
      let keys = Object.keys(values);
      keys.forEach(d => {
        values[d] = values[d] === null ? undefined : values[d];
      });

      values.regionId = values.regionPath ? values.regionPath[values.regionPath.length - 1] : 0

      if (values.addr !== undefined) {
        let addrObj = addrList[values.addr];
        if (addrObj) {
          values.address = `${addrObj.address}（${addrObj.name}）`
          values.lng = addrObj.location.lng;
          values.lat = addrObj.location.lat;
        }
      }

      dispatch({
        type: 'PMchInfo/location',
        payload: values,
        callback: () => {
          onCancel();
          setTablePayload({...tablePayload});
        },
      });
    });
  }

  /* 取消操作 */
  function onCancel() {
    setLocationForm(undefined);
    setAddrList([]);
    setValue(null);
    form.resetFields();
  }

  /* 查询并回填数据 */
  const handleSearch = (newValue) => {
    let regionPath = form.getFieldValue("regionPath");
    if (!regionPath || regionPath.length <= 0) {
      message.error("请先选择所在区县").then();
      return;
    }

    let regionId = regionPath[regionPath.length - 2];
    let regionObj = regionList.find(d => d.id === regionId);
    fetch(regionObj.name, newValue, setAddrList);
  };

  /* 设置值 */
  const handleChange = (newValue) => {
    setValue(newValue);
  };

  return (
    <Modal
      confirmLoading={submitting}
      title={locationForm ? locationForm.title : ''}
      open={locationForm ? locationForm.visible : false}
      onOk={onOk}
      onCancel={onCancel}
      forceRender={true}
      width={700}
      bodyStyle={{
        paddingTop: 24,
        maxHeight: 420,
        overflowY: 'auto',
        overflowX: 'hidden',
        paddingRight: 17
      }}
    >
      <Form layout='horizontal' labelCol={{span: 4}} form={form}>
        {locationForm && locationForm.data && (
          <Form.Item name='id' hidden={true}>
            <Input/>
          </Form.Item>
        )}
        {locationForm && locationForm.data && locationForm.data.address && (
          <Row gutter={16}>
            <Col span={24}>
              <Form.Item name='address' label='当前定位'>
                <Input disabled={true}/>
              </Form.Item>
            </Col>
          </Row>
        )}
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              name='regionPath' label='所在区县'
              rules={[
                {required: true, message: '所在区县不能为空'},
              ]}>
              <Cascader
                placeholder='请选择所在区县'
                options={regionTree}
                expandTrigger="hover"
              />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              name='addr' label='详细地址'
              rules={[
                {required: true, message: '详细地址不能为空'},
              ]}>
              <Select
                showSearch
                value={value}
                placeholder={'请选择详细地址'}
                defaultActiveFirstOption={false}
                suffixIcon={null}
                filterOption={false}
                onSearch={handleSearch}
                onChange={handleChange}
                notFoundContent={null}
                options={(addrList || []).map((d, i) => ({
                  value: i,
                  label: `${d.address}（${d.name}）`,
                }))}
              />
            </Form.Item>
          </Col>
        </Row>

      </Form>
    </Modal>
  );
};


export default connect(({loading, SystemCommon}) => {
  return {
    submitting: loading.effects['PMchInfo/location'],
    regionTree: SystemCommon.regionTree,
    regionList: SystemCommon.regionList,
  };
})(LocationForm);

